
import LoginUserSetting from "@/pages/LoginUserSetting";
import {clearAuthInfo} from '@/utils/auth';
import {KeepAliveContext} from "@umijs/max";
import {LogoutOutlined, UserOutlined} from '@ant-design/icons';
import {history, useModel} from '@umijs/max';
import {Avatar, Menu} from 'antd';
import {KfModal, useKeepAliveContext} from "kf-web-library";
import {stringify} from 'querystring';
import type {MenuInfo} from 'rc-menu/lib/interface';
import React, {useCallback, useState} from 'react';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import { ItemType } from 'antd/lib/menu/interface';

interface AvatarDropdownProps {
}

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {
  // api.logout
  clearAuthInfo();

  const {search, pathname} = history.location;
  const urlParams = new URL(window.location.href).searchParams;
  /** 此方法会跳转到 redirect 参数所在的位置 */
  const redirect = urlParams.get('redirect');
  // Note: There may be security issues, please note
  if (window.location.pathname !== '/login' && !redirect) {
    history.replace({
      pathname: '/login',
      search: stringify({
        redirect: pathname + search,
      }),
    });
  }
};

const AvatarDropdown: React.FC<AvatarDropdownProps> = (props) => {
  const {initialState, setInitialState} = useModel('@@initialState');
  const userInfo = initialState?.currentUserInfo;
  const [loginUserSettingModalOpen, setLoginUserSettingModalOpen] = useState(false);

  const {
    keepElements,
    dropByCacheKey,
  } = useKeepAliveContext() || {};

  const menuItems: ItemType[] = [
    {
      key: 'loginUserSetting',
      icon: <UserOutlined/>,
      label: '个人信息',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined/>,
      label: '退出登录',
    },
  ];

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const {key} = event;
      if (key === 'loginUserSetting') {
        setLoginUserSettingModalOpen(true);
      } else if (key === 'logout') {
        //注销前, 先把InitialState 和 keepTabs清空
        setInitialState((s) => ({...s, currentUserInfo: undefined, frontMenus: undefined}));
        Object.entries(keepElements?.current).forEach(([key]) => {
          dropByCacheKey?.(key);
        });
        loginOut();
        return;
      }
      //history.push(`/account/${key}`);
    },
    [setInitialState],
  );


  return (
    <>
      <HeaderDropdown menu={{ items: menuItems, selectedKeys: [],className: styles.menu, onClick: onMenuClick }} trigger={['click']}>
        <span className={`kf-avatar-action-item ant-pro-global-header-header-actions-avatar`}>
          <Avatar icon={<UserOutlined />} size={40} />
          <span className={'kf-avatar-username'}>{userInfo?.nickname}</span>
        </span>
      </HeaderDropdown>

      {loginUserSettingModalOpen && (
        <KfModal
          title={`「${userInfo?.nickname}」 - 个人信息`}
          width={720}
          bodyStyle={{ padding: '0 24px' }}
          open={true}
          onCancel={() => setLoginUserSettingModalOpen(false)}
          onSubmitted={() => {
            return false;
          }}
        >
          <LoginUserSetting />
        </KfModal>
      )}
    </>
  );
};

export default AvatarDropdown;
